/*
 * Copyright (C) 2019-2020 Alibaba Group Holding Limited
 */

#include <stdio.h>
#include <stdlib.h>
#include <aos/aos.h>

#include "alg_huazhen.h"
#include "hz_asr.h"

#define TAG "AIHZ"

#define PROCESS_TIME_MS     30
#define PROCESS_SAMPLES     (PROCESS_TIME_MS * 16)

static int alg_hz_init(mvoice_event_cb cb, void *user_data);
static int alg_hz_deinit();
static int alg_hz_asr_proc(void *mic);
static void *g_user_data;

static mvoice_event_cb mvoice_alg_callback;

mvoice_alg_t g_alg_huazhen = {
    .name = "huazhen",
    .data_format = {
        .interleaved = 0,
        .samples_per_frame = PROCESS_SAMPLES,
        .samples_bits = 16,
        .sample_freq = 16000,
    },
    .init = alg_hz_init,
    .deinit = alg_hz_deinit,
    .kws_proc = NULL,
    .asr_proc = alg_hz_asr_proc,
};

static int alg_hz_init(mvoice_event_cb cb, void *user_data)
{
    mvoice_alg_callback = cb;
    g_user_data = user_data;

    if (Wanson_ASR_Init() < 0) 
    {
		LOGE(TAG, "Wanson_ASR_Init Failed!");
		return -1;
	}
    Wanson_ASR_Reset();

    return 0;
}

static int alg_hz_deinit()
{
    return 0;
}

static int alg_hz_asr_proc(void *mic)
{
    const char *text;
	float score;
    int ret;

    ret = Wanson_ASR_Recog((short*)mic, PROCESS_SAMPLES, &text, &score);  

    if (ret == 1 && text) {
        LOGD(TAG, "ASR Result: %s\n", text);
        VAG_CB(MVC_EVT_ASR, (void *)text, strlen(text) + 1, g_user_data);
    } else if (ret < 0) {
        LOGE(TAG, "asr error %d", ret);
    }

    return 0;
}

void *alg_huazhen_obj_get(void)
{
    return &g_alg_huazhen;
}

// #include "xiaomei.h"
// int ai_hz_test()
// {
//     int frame_bytes = PROCESS_SAMPLES * 2;

//     alg_hz_init(NULL, NULL);

//     for (int i = 0; i < sizeof(xiaomei_raw) / frame_bytes; i++) {
//         alg_hz_asr_proc(NULL, &xiaomei_raw[frame_bytes * i], NULL, NULL);
//     }
// }